package com.lanhai.fnstore;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.log4j.Logger;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

/**
 * websocket相关
 * @author virus408
 *
 */
public class WebSocketCore {
	 
	private static WebSocketClient wsClient=null;
	private static final Logger logger = Logger.getLogger(WebSocketCore.class);
	
	
	public WebSocketCore(String ip) { 
		try {
			String url = "ws://" + ip + ":8012/echo/username=sys&src=svr";
			wsClient = new WebSocketClient(new URI(url), new Draft_6455()) {
				@Override
				public void onOpen(ServerHandshake serverHandshake) {
					logger.info("握手成功！");
				}

				@Override
				public void onMessage(String msg) {
					logger.info("收到消息==========" + msg);
					if (msg.equals("over")) {
						wsClient.close();
					}
				}

				@Override
				public void onClose(int i, String s, boolean b) {
					logger.info("链接已关闭");
					wsClient = null;
				}

				@Override
				public void onError(Exception e) {
					e.printStackTrace();
					logger.info("发生错误已关闭");
					wsClient = null;
				}
			};
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		wsClient.connect();
	}
	
	
	public void sendMsgByWs(int agvid, String msg) {
		if (wsClient == null) {
			logger.error("没有websocket连接，无法发送消息！");
		} else {
			String msgp = "{receiver:'no" + agvid + "_agv',data:'" + msg + "'}";
			wsClient.send(msgp);
		}
	}

	public void Stop() {
		wsClient.close();
		wsClient = null;
	}

}
